package com.qf.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsAdminMapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.mapper.DtsRoleMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.util.AuthSupport;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 授权
 *
 *   RBAC模式 ：
 *
 *     Role base aut..  control 基于角色验证控制
 *     用户名  关联表    角色表  关联表   权限表
 *
 * @author lixu
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {


    @Autowired
    private DtsAdminMapper dtsAdminMapper;
    @Autowired
    private DtsRoleMapper dtsRoleMapper;
    @Autowired
    private DtsPermissionMapper dtsPermissionMapper;
    /**
     * 授权  当前登录用户的真实权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        DtsAdmin dtsAdmin = (DtsAdmin) principals.getPrimaryPrincipal();
        //角色ID 集合
        Integer[] roleIds = dtsAdmin.getRoleIds();

        //1:查询角色集合 （当前用户拥有的）
        List<DtsRole> dtsRoleList = dtsRoleMapper.selectBatchIds(Arrays.asList(roleIds));
        Set<String> roleNames = dtsRoleList.stream().map(DtsRole::getName).collect(Collectors.toSet());
        //-------------------------------------------------------
        //2:查询权限集合 （当前用户拥有的）
        List<DtsPermission> dtsPermissionList = dtsPermissionMapper.selectList(new QueryWrapper<DtsPermission>()
                .in("role_id", roleIds));
        Set<String> permissionList = dtsPermissionList.stream()
                .map(DtsPermission::getPermission).collect(Collectors.toSet());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleNames);
        authorizationInfo.setStringPermissions(permissionList);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        //用户名
        //加密后密码
        DtsAdmin dtsAdmin = dtsAdminMapper.selectOne(new QueryWrapper<DtsAdmin>()
                .eq("username", username));
        if(null == dtsAdmin){
            throw new UnknownAccountException();
        }
        if(!new BCryptPasswordEncoder().matches(password,dtsAdmin.getPassword())){
            throw new IncorrectCredentialsException();
        }
        //逻辑删除 ：  用户正常：0   用户被删除 ： 1  被锁定：2
        if(dtsAdmin.getDeleted()){
            //用户被锁定
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(dtsAdmin,password,this.getName()) ;
    }
}
